using BasicData.API.Application.Command;
using BasicData.API.Dtos;
using BasicData.Domain.Entities;
using BasicData.ErrorCode;
using BasicData.Infrastructure.Interfasce;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace BasicData.API.Application.CommandHandlers
{
    /// <summary>
    /// 添加商品命令处理器
    /// </summary>
    public class AddGoodsCommandHandler : IRequestHandler<AddGoodsCommand, APIResult<GoodsDTO>>
    {
        private readonly IBaseRepositroy<Goods> _goodsRepository;
        private readonly ILogger<AddGoodsCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="goodsRepository">商品仓储</param>
        /// <param name="logger">日志</param>
        public AddGoodsCommandHandler(IBaseRepositroy<Goods> goodsRepository, ILogger<AddGoodsCommandHandler> logger)
        {
            _goodsRepository = goodsRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理添加商品命令
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消标记</param>
        /// <returns>添加结果</returns>
        public async Task<APIResult<GoodsDTO>> Handle(AddGoodsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始添加商品，商品名称：{GoodsName}", request.GoodsName);

                // 创建商品实体
                var goods = new Goods
                {
                    GoodsName = request.GoodsName,
                  
                };

                // 添加商品
                await _goodsRepository.AddAsync(goods);
           

                _logger.LogInformation("成功添加商品，ID：{GoodsId}", goods.GoodsId);

                // 转换为DTO
                var goodsDTO = new GoodsDTO
                {
                    GoodsId = goods.GoodsId,
                    GoodsName = goods.GoodsName,
                 
                };

                return new APIResult<GoodsDTO>
                {
                    Code = ResultCode.添加成功,
                    Message = "添加商品成功",
                    Data = goodsDTO
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加商品时发生错误");
                return new APIResult<GoodsDTO>
                {
                    Code = ResultCode.添加失败,
                    Message = $"添加商品失败: {ex.Message}"
                };
            }
        }
    }
} 